package com.notary.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import com.notary.entity.NotaryVideo;
import com.notary.entity.po.ContractDTO;
import com.notary.entity.po.H5FaceDTO;
import com.notary.entity.vo.JsonResult;
import com.notary.seal.PersonalRegisterRequest;
import com.notary.service.NotaryCoordinateService;
import com.notary.service.NotaryVideoService;
import com.notary.service.SysUserService;
import com.notary.util.HttpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
* <p>
* 公证员视频 前端控制器
* </p>
* @author nicai
* @since 2020-12-07
*/


@Api(tags = "公证员视频控制器")
@RequestMapping("/notaryVideo")
@RestController
@Slf4j
public class NotaryVideoController{


    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Value("${tencent.face.version}")
    private String version;

    @Value("${tencent.face.appid}")
    private String appid;

    @Value("${tencent.face.secret}")
    private String secret;

    @Autowired
    private SysUserService sysUserService;



    NotaryVideoService notaryVideoService;


    NotaryCoordinateService notaryCoordinateService;
    @Autowired
    public  NotaryVideoController(NotaryVideoService notaryVideoService){
         this.notaryVideoService = notaryVideoService;
    }


    /**
        *<P>
        * 根据ID查找返回单个对象
        *</P>
    */
    @ApiOperation(value = "根据id查询")
    @GetMapping("/getByNotaryId/{notaryId}")
    public JsonResult  getByNotaryId(@PathVariable("id") Integer id) {
         return JsonResult.success(notaryVideoService.getByNotaryId(id));
    }


    /**
        *<p>
        * 保存对象-如果对象存在则修改原数据，否则插入一条新数据
        *</p>
    */
    @ApiOperation(value = "保存对象")
    @PostMapping("/saveOrUpdate")
    @Transactional(rollbackFor = Exception.class)
    public JsonResult saveOrUpdate(@RequestBody NotaryVideo notaryVideo)throws Exception {

            if(notaryVideo.getNotaryId() == null){
                return JsonResult.fail("notaryId不能为空");
            }

            if(!StringUtils.isNotEmpty(notaryVideo.getUrl())){
                return JsonResult.fail("url不能为空");
            }

            if(notaryVideo.getId() == null){
                QueryWrapper<NotaryVideo> queryWrapper= new QueryWrapper<NotaryVideo>();
                queryWrapper.eq("notary_id", notaryVideo.getNotaryId());
                if(notaryVideoService.getOne(queryWrapper) != null) {
                    return JsonResult.fail("已存在告知视频");
                }
            }
        notaryVideo.setType("0");
        return JsonResult.success(notaryVideoService.saveOrUpdate(notaryVideo));
    }

    @ApiOperation(value = "预览 富文本")
    @PostMapping ("/preview")
    public JsonResult preview(@RequestBody ContractDTO dto, HttpServletRequest request) {
        return notaryVideoService.preview(dto,request);
    }

    /**
     * 身份认证查询接口
     */
    @ApiOperation(value = "H5身份认证查询接口")
    @ApiResponses(value = { @ApiResponse(code = 200, message = "身份认证查询接口", response = JsonResult.class) })
    @PostMapping("/getResultH5")
    // @LoginOfficeUserFaceRequired
    public JsonResult getResultH5(@RequestBody H5FaceDTO dto){
        String access_token=get_access_token();
        String NONCE_ticket=get_SIGN_ticket(access_token);
        List<String> listStr=new ArrayList();
        listStr.add(appid);
        listStr.add(dto.getOrderNo());
        listStr.add(version);
        String nonceStr=getItemID(32);
        //nonceStr
        listStr.add(nonceStr);
        String url="https://idasc.webank.com/api/server/sync";
        String sign=sign(listStr,NONCE_ticket);
        HashMap queryParas = new HashMap ();
        queryParas.put("app_id",appid);
        queryParas.put("version",version);
        queryParas.put("nonce",nonceStr);
        queryParas.put("order_no",dto.getOrderNo());
        queryParas.put("sign",sign);
        log.info("H5返回校验结果请求参数："+queryParas);
        String result= HttpUtils.get(url,queryParas);
        JSONObject jsonObject = JSON.parseObject(result);
        log.info("H5返回校验结果："+jsonObject);
        String code=jsonObject.getString("code");
     /*   if(code.equals("0")){
            return   JSONResult.success("");
        }else{
            return   JSONResult.fail(jsonObject.getString("msg"));
        }
*/

        if(code.equals("0")){
            return   JsonResult.success("");
        }else{
            //人脸匹配度
            if(code.equals("66660004")){
                String returStr=jsonObject.getString("result");
                JSONObject jsonObject1=JSON.parseObject(returStr);
                BigDecimal similarity=jsonObject1.getBigDecimal("similarity");
                if(similarity.compareTo(new BigDecimal(75))>-1 ){
                    return   JsonResult.success("");
                }else{
                    return   JsonResult.fail(jsonObject.getString("msg"));
                }
            }
            return   JsonResult.fail(jsonObject.getString("msg"));
        }


    }
    private String get_access_token(){
        JSONObject jsonObject = new JSONObject();
        String url="https://idasc.webank.com/api/oauth2/access_token?app_id="+appid+"&secret="+secret+
                "&grant_type=client_credential&version="+version;
        String body = jsonObject.toJSONString();
        System.out.println("body = " + body);
        String result=HttpUtils.get(url);
        log.info("result=get_access_token:"+result);
        JSONObject jsonObject1 = JSON.parseObject(result);

        String code=jsonObject1.getString("code");

        JSONObject returnJson = new JSONObject();
        if(code.equals("0")){
            String access_token=jsonObject1.getString("access_token");
            log.info("access_token:"+access_token);
            returnJson.put("cdoe","0");
            returnJson.put("data",access_token);
            return access_token;
        }else{
            returnJson.put("code",1);
            returnJson.put("data",returnJson.getString("msg"));
            return "1";
        }


    }


    private String get_SIGN_ticket(String access_token){
        String url=" https://idasc.webank.com/api/oauth2/api_ticket?app_id="+appid+"&access_token="+access_token+
                "&type=SIGN&version="+version;
        String result=HttpUtils.get(url);
        log.info("result=get_SIGN_ticket:"+result);
        JSONObject jsonObject = JSON.parseObject(result);
        String code=jsonObject.getString("code");
        if(code.equals("0")){
            String a=jsonObject.getString("tickets");
            jsonObject= JSONArray.parseArray(a).getJSONObject(0);
            String SIGN_ticket=jsonObject.getString("value");
            log.info("SIGN_ticket:"+SIGN_ticket);
            return  SIGN_ticket;
        }else{
            return  "1";
        }

    }
    private String get_NONCE_ticket(String access_token,String userId){
        String url=" https://idasc.webank.com/api/oauth2/api_ticket?app_id="+appid+"&access_token="+access_token+
                "&type=NONCE&version="+version+"&user_id="+userId;

        String result=HttpUtils.get(url);
        log.info("result=get_NONCE_ticket:"+result);
        JSONObject jsonObject= JSON.parseObject(result);
        String code=jsonObject.getString("code");
        if(code.equals("0")){
            String a=jsonObject.getString("tickets");
            jsonObject=JSONArray.parseArray(a).getJSONObject(0);
            String NONCE_ticket=jsonObject.getString("value");
            log.info("NONCE_ticket:"+NONCE_ticket);
            return NONCE_ticket;
        }else{
            return "1";
        }

    }
    private JSONObject getFaceId(String appid,String orderNo,String name,String idNo,String userId,String SIGN_ticket,String version){
        String url="https://idasc.webank.com/api/server/h5/geth5faceid";
        JSONObject queryParas = new JSONObject();
        queryParas.put("webankAppId",appid);
        queryParas.put("orderNo",orderNo);
        queryParas.put("name",name);
        queryParas.put("idNo",idNo);
        queryParas.put("userId",userId);
        queryParas.put("version",version);
        List<String>listStr=new ArrayList();
        listStr.add("1.0.0");
        listStr.add(idNo);
        listStr.add(appid);
        listStr.add(orderNo);
        listStr.add(name);
        listStr.add(userId);
        queryParas.put("sign",sign(listStr,SIGN_ticket));
        log.info("======sign"+sign(listStr,SIGN_ticket ));
        String body = queryParas.toJSONString();
        String result=HttpUtils.post(url,body,"application/json");
        log.info("result:"+result);
        JSONObject jsonObject = JSON.parseObject(result);
        String code=jsonObject.getString("code");

        JSONObject returnJson = new JSONObject();

        if(code.equals("0")){
            String h5faceId=jsonObject.getJSONObject("result").getString("h5faceId");
            log.info("h5faceId:"+h5faceId);
            returnJson.put("code",0);
            returnJson.put("data",h5faceId);
            // return h5faceId;
            return  returnJson;
        }else{
            returnJson.put("code",1);
            returnJson.put("msg",jsonObject.getString("msg"));
            // return "1";
            return  returnJson;
        }

    }

    public static String sign(List<String> values, String ticket) {
        if (values == null) {
            throw new NullPointerException("values is null");
        }
        values.removeAll(Collections.singleton(null));// remove null
        values.add(ticket);
        java.util.Collections.sort(values);

        StringBuilder sb = new StringBuilder();
        for (String s : values) {
            sb.append(s);
        }
        return Hashing.sha1().hashString(sb, Charsets.UTF_8).toString().toUpperCase();
    }
    private static String getItemID( int n )
    {
        String val = "";
        Random random = new Random();
        for ( int i = 0; i < n; i++ )
        {
            String str = random.nextInt( 2 ) % 2 == 0 ? "num" : "char";
            if ( "char".equalsIgnoreCase( str ) )
            { // 产生字母
                int nextInt = random.nextInt( 2 ) % 2 == 0 ? 65 : 97;
                // System.out.println(nextInt + "!!!!"); 1,0,1,1,1,0,0
                val += (char) ( nextInt + random.nextInt( 26 ) );
            }
            else if ( "num".equalsIgnoreCase( str ) )
            { // 产生数字
                val += String.valueOf( random.nextInt( 10 ) );
            }
        }
        return val;
    }

    /**
     *<p>
     * 根据 模板id和人员id查询当前坐标
     *</p>
     */
    @ApiOperation(value = "据 模板id和人员id查询当前坐标")
    @GetMapping("/getByTemplate/{templateId}")
    public JsonResult getByTemplate(@PathVariable("templateId") String templateId, HttpServletRequest request) {
        return notaryVideoService.getByTemplate(templateId,request);
    }

    /**
     *<p>
     * 用户签名
     *</p>
     */
    @ApiOperation(value = " 用户签名")
    @PostMapping("/applyPersonalRegister")
    public JsonResult applyPersonalRegister(PersonalRegisterRequest vo, MultipartFile file) {
        return  notaryVideoService.applyPersonalRegister(vo,file);
    }
}

                       